<?php

namespace plugin\ai\app\admin\controller;

use plugin\admin\app\common\Util;
use plugin\ai\app\service\Common;
use support\Request;
use support\Response;
use plugin\ai\app\model\AiModel;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 模型设置 
 */
class AiModelController extends Crud
{
    
    /**
     * @var AiModel
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new AiModel;
    }

    /**
     * @param Request $request
     * @return void
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        AiModel::init();
        return parent::select($request);
    }

    /**
     * 通用格式化
     * @param $items
     * @param $total
     * @return Response
     */
    protected function formatNormal($items, $total): Response
    {
        if (count($items) == 1) {
            $item = current($items);
            $settings = $item->settings ?? [];
            $handler = $item->handler;
            if (class_exists($handler) && property_exists($handler, 'defaultSettings')) {
                $defaultSettings = $handler::$defaultSettings;
                foreach ($defaultSettings as $key => $defaultSetting) {
                    if (!isset($settings[$key])) {
                        $settings[$key] = $defaultSetting;
                    }
                }
            }
            $item->settings = $settings;
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('ai-model/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $settings = $request->post('settings');
            $settings = json_decode($settings, true);
            if (!is_array($settings)) {
                throw new BusinessException('"设置"字段json格式错误');
            }
            $handler = $request->post('handler');
            if (!$handler) {
                throw new BusinessException("处理器不能为空");
            }
            return parent::insert($request);
        }
        return view('ai-model/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            [$id, $data] = $this->updateInput($request);
            $model = AiModel::find($id);
            $settings = $model->settings;
            $handler = $model->handler;
            if (class_exists($handler) && property_exists($handler, 'defaultSettings')) {
                $defaultSettings = $handler::$defaultSettings;
                foreach ($defaultSettings as $key => $defaultSetting) {
                    if (!isset($settings[$key])) {
                        $settings[$key] = $defaultSetting;
                    }
                }
            }
            if (isset($data['models'])) {
                foreach ($settings as $key => $item) {
                    $value = $request->post($key);
                    switch ($item['type'] ?? '') {
                        case 'number':
                            $settings[$key]['value'] = (int)$value;
                            break;
                        case 'checkbox':
                            $settings[$key]['value'] = (bool)$value;
                            break;
                        default:
                            $settings[$key]['value'] = $value;
                            break;
                    }
                }
                $data['settings'] = json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                $models = isset($data['models']) ? explode("\n", $data['models']) : $model->models;
                $data['models'] = implode("\n", array_unique($models));
                if (!empty($settings['allowNetwork']['value'])) {
                    $openaiVersion = Util::getPackageVersion('webman/openai');
                    if ($openaiVersion === 'unknown' || version_compare($openaiVersion, '1.0.7', '<')) {
                        throw new BusinessException('请执行<br> composer require webman/openai ^1.0.7 <br>升级 webman/openai 并重启webman');
                    }
                }
            }
            $this->doUpdate($id, $data);
            return $this->json(0);
        }
        return view('ai-model/update');
    }

    /**
     * 获取模型类型
     * @return Response
     */
    public function modelTypes(): Response
    {
        $modelTypes = Common::getModelTypes();
        $modelTypesVisible = Common::getModelTypes(true);
        $items = [];
        foreach ($modelTypes as $key => $name) {
            $items[$key] = [
                'name' => $name,
                'visible' => isset($modelTypesVisible[$key]),
            ];
        }
        return json(['code' => 0, 'msg' => 'ok', 'data' => $items]);
    }

}
